<template>
  <transition v-if="false" :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
    <div v-show="showSearch" class="mb-[10px]">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="应用ID" prop="appId">
            <el-input v-model="queryParams.appId" placeholder="请输入应用ID" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="支付平台ID" prop="payTypeId">
            <el-input v-model="queryParams.payTypeId" placeholder="请输入支付平台ID" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="收款账号ID" prop="accountId">
            <el-input v-model="queryParams.accountId" placeholder="请输入收款账号ID" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option v-for="dict in app_account_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="总额度" prop="totalLimit">
            <el-input v-model="queryParams.totalLimit" placeholder="请输入总额度" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="额度增长率" prop="increaseRate">
            <el-input v-model="queryParams.increaseRate" placeholder="请输入额度增长率" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="额度刷新时间" prop="refreshTime">
            <el-input v-model="queryParams.refreshTime" placeholder="请输入额度刷新时间" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="最小订单金额" prop="minMoney">
            <el-input v-model="queryParams.minMoney" placeholder="请输入最小订单金额" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="最大订单金额" prop="maxMoney">
            <el-input v-model="queryParams.maxMoney" placeholder="请输入最大订单金额" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="收款总金额" prop="totalMoney">
            <el-input v-model="queryParams.totalMoney" placeholder="请输入收款总金额" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="支付方式" prop="payMethod">
            <el-input v-model="queryParams.payMethod" placeholder="请输入支付方式" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="收款方式" prop="receiveList">
            <el-input v-model="queryParams.receiveList" placeholder="请输入收款方式" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="失败次数限制" prop="failLimit">
            <el-input v-model="queryParams.failLimit" placeholder="请输入失败次数限制" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="queryParams.sort" placeholder="请输入排序" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="商户ID" prop="clientId">
            <el-input v-model="queryParams.clientId" placeholder="请输入商户ID" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="代理ID" prop="agentId">
            <el-input v-model="queryParams.agentId" placeholder="请输入代理ID" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </transition>

  <el-card shadow="never">
    <template #header>
      <div class="flex justify-between pr-1">
        <div class="flex gap-8">
          <span>收款账号</span>
          <span class="text-[red]">(数值越大，优先级越高)</span>
        </div>
        <el-icon class="hover:text-[var(--el-color-primary)] cursor-pointer text-[20px]" @click="setFirst"><CloseBold /></el-icon>
      </div>
    </template>

    <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
    <el-button plain icon="Refresh" circle @click="getList"></el-button>
    <el-table v-loading="loading" :data="PayAppAccountList" class="mt-[10px]" style="height: 64vh" @row-dblclick="handleUpdate">
      <el-table-column v-if="false" label="主键ID" align="center" prop="id" />
      <el-table-column v-if="false" label="商户名称" align="center" prop="clientName" />
      <el-table-column v-if="false" label="代理名称" align="center" prop="agentName" />
      <el-table-column label="账号名称" align="center" show-overflow-tooltip prop="accountName" />
      <el-table-column label="状态" align="center" prop="status" width="60">
        <template #default="scope">
          <dict-tag :options="app_account_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="自动上线" align="center" show-overflow-tooltip prop="autoUp" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.autoUp == 1" type="success">开启</el-tag>
          <el-tag v-else type="info">关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总额度/剩余额度" align="center">
        <template #default="{ row }">
          <div v-if="row.totalLimit > 0">
            <el-tooltip class="box-item" effect="dark" :content="'总额度：' + row.totalLimit" placement="top">
              <div class="truncate">
                {{ row.totalLimit }}
              </div>
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" :content="'剩余额度：' + row.limitMoney" placement="top">
              <div class="truncate">
                {{ row.limitMoney }}
              </div>
            </el-tooltip>
          </div>
          <div v-else>不限制</div>
        </template>
      </el-table-column>
      <el-table-column label="订单金额限制" align="center">
        <template #default="{ row }">
          <div v-if="row.maxMoney > 0" class="flex items-center justify-center">
            <div class="truncate">
              {{ row.minMoney }}
            </div>
            -
            <div class="truncate">
              {{ row.maxMoney }}
            </div>
          </div>
          <div v-else>不限制</div>
        </template>
      </el-table-column>
      <el-table-column label="额度增长率" align="center" width="90" prop="increaseRate" />
      <el-table-column label="刷新时间" align="center" prop="refreshTime" width="80" />
      <el-table-column v-if="false" label="最大金额" align="center" prop="maxMoney" />``
      <el-table-column v-if="false" label="支付方式" align="center" prop="payMethod" />
      <!--        <el-table-column label="收款方式" align="center" prop="receiveList" />-->
      <el-table-column v-if="false" label="失败次数限制" align="center" prop="failLimit" />
      <el-table-column label="排序" align="center" prop="sort" width="50" />
      <el-table-column label="操作" align="center" width="80px" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-tooltip content="配置" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      :page-sizes="[20, 30, 50, 100]"
      v-model:limit="queryParams.pageSize"
      :total="total"
      @pagination="getList"
    />
  </el-card>
  <!-- 添加或修改应用收款账号对话框 -->
  <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
    <el-form ref="PayAppAccountFormRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio v-for="dict in app_account_status" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="总额度" prop="totalLimit">
        <el-input v-model="form.totalLimit" placeholder="请输入总额度" />
      </el-form-item>
      <el-form-item label="额度增长率" prop="increaseRate">
        <el-input v-model="form.increaseRate" placeholder="请输入额度增长率" />
      </el-form-item>
      <el-form-item label="额度刷新时间" prop="refreshTime">
        <el-input v-model="form.refreshTime" placeholder="请输入额度刷新时间" />
      </el-form-item>
      <el-form-item label="最小订单金额" prop="minMoney">
        <el-input v-model="form.minMoney" placeholder="请输入最小订单金额" />
      </el-form-item>
      <el-form-item label="最大订单金额" prop="maxMoney">
        <el-input v-model="form.maxMoney" placeholder="请输入最大订单金额" />
      </el-form-item>
      <el-form-item label="收款总金额" prop="totalMoney">
        <el-input v-model="form.totalMoney" placeholder="请输入收款总金额" />
      </el-form-item>
      <el-form-item label="支付方式" prop="payMethod">
        <el-input v-model="form.payMethod" placeholder="请输入支付方式" />
      </el-form-item>
      <el-form-item label="收款方式" prop="receiveList">
        <el-input v-model="form.receiveList" type="textarea" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item label="失败次数限制" prop="failLimit">
        <el-input v-model="form.failLimit" placeholder="请输入失败次数限制" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="form.sort" placeholder="请输入排序" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="PayAppAccount" lang="ts">
import { listPayAppAccount, getPayAppAccount, delPayAppAccount, addPayAppAccount, updatePayAppAccount } from '@/api/pay/PayAppAccount';
import { PayAppAccountVO, PayAppAccountQuery, PayAppAccountForm } from '@/api/pay/PayAppAccount/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { app_account_status } = toRefs<any>(proxy?.useDict('app_account_status'));
const props = defineProps({
  plateInfo: {
    type: Object,
    default: () => {}
  }
});
watch(
  () => props.plateInfo.id,
  (val) => {
    if (val) {
      console.log(val, 'valval');

      getList();
    }
  },
  { deep: true }
);

const PayAppAccountList = ref<PayAppAccountVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const PayAppAccountFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PayAppAccountForm = {
  status: undefined,
  totalLimit: undefined,
  increaseRate: undefined,
  refreshTime: undefined,
  minMoney: undefined,
  maxMoney: undefined,
  totalMoney: undefined,
  payMethod: undefined,
  receiveList: undefined,
  failLimit: undefined,
  sort: undefined
};
const data = reactive<PageData<PayAppAccountForm, PayAppAccountQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    groupId: undefined,
    payTypeId: undefined,
    accountId: undefined,
    status: undefined,
    totalLimit: undefined,
    increaseRate: undefined,
    refreshTime: undefined,
    minMoney: undefined,
    maxMoney: undefined,
    totalMoney: undefined,
    payMethod: undefined,
    receiveList: undefined,
    failLimit: undefined,
    sort: undefined,
    clientId: undefined,
    agentId: undefined,
    groupTypeId: undefined,
    params: {}
  },
  rules: {
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    totalLimit: [{ required: true, message: '总额度不能为空', trigger: 'blur' }],
    increaseRate: [{ required: true, message: '额度增长率不能为空', trigger: 'blur' }],
    refreshTime: [{ required: true, message: '额度刷新时间不能为空', trigger: 'blur' }],
    minMoney: [{ required: true, message: '最小订单金额不能为空', trigger: 'blur' }],
    maxMoney: [{ required: true, message: '最大订单金额不能为空', trigger: 'blur' }],
    totalMoney: [{ required: true, message: '收款总金额不能为空', trigger: 'blur' }],
    payMethod: [{ required: true, message: '支付方式不能为空', trigger: 'blur' }],
    receiveList: [{ required: true, message: '收款方式不能为空', trigger: 'blur' }],
    failLimit: [{ required: true, message: '失败次数限制不能为空', trigger: 'blur' }],
    sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询应用收款账号列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.groupId = props.plateInfo.groupId;
  queryParams.value.groupTypeId = props.plateInfo.id;
  const res = await listPayAppAccount(queryParams.value);
  PayAppAccountList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  PayAppAccountFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PayAppAccountVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  emits('changeType', 'add');
  emits('changeConfig', PayAppAccountList.value);
};

const emits = defineEmits(['changeConfig', 'changeType', 'setFirst']);
/** 修改按钮操作 */
const handleUpdate = async (row?: PayAppAccountVO, column?: any) => {
  if (!(column && column.label == '操作')) {
    emits('changeConfig', row);
    emits('changeType', 'edit');
  }
};
const setFirst = () => {
  emits('setFirst');
};

/** 提交按钮 */
const submitForm = () => {
  PayAppAccountFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updatePayAppAccount(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPayAppAccount(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PayAppAccountVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除 ' + row.accountName + ' 收款账号').finally(() => (loading.value = false));
  await delPayAppAccount(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/PayGroupAccount/export',
    {
      ...queryParams.value
    },
    `PayAppAccount_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});

defineExpose({ getList });
</script>

<style lang="scss" scoped>
.el-card {
  min-height: 100%;
  position: relative;
  padding-bottom: 40px;
}
.pagination-container {
  position: absolute;
  left: 50%;
  bottom: 10px;
  transform: translateX(-50%);
}
</style>
